package com.ccloud.modules.motorfactory.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccloud.api.motorfactory.domain.MApplicationMotorModel;
import com.ccloud.api.motorfactory.domain.MMainEnginePlants;
import com.ccloud.api.motorfactory.domain.MMotorPart;
import com.ccloud.api.motorfactory.domain.MPartType;
import com.ccloud.api.motorfactory.dto.MotorPartExcelDto;
import com.ccloud.api.motorfactory.listener.MotorPartExcelListener;
import com.ccloud.api.motorfactory.service.IMApplicationMotorModelService;
import com.ccloud.api.motorfactory.service.IMMainEnginePlantsService;
import com.ccloud.api.motorfactory.service.IMMotorPartService;
import com.ccloud.api.motorfactory.service.IMPartTypeService;
import com.ccloud.common.core.reqres.response.Result;
import com.ccloud.common.core.utils.OauthUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author chentl
 * @Version V1.0
 * @Project wh-bigdata-frame.
 * @Title MotorPartController.java
 * @Description 摩托零件货品 控制器
 * @Package com.ccloud.api.motorfactory.controller
 * @Date 2022/4/9 17:52
 * @Copyright: 武汉大数据产业发展有限公司 All rights reserved.
 */
@Slf4j
@RestController
@RequestMapping("/motor-part")
public class MotorPartController {

    @Resource
    private IMMotorPartService motorPartService;

    @Resource
    private IMApplicationMotorModelService applicationMotorModelService;

    @Resource
    private IMPartTypeService partTypeService;

    @Resource
    private IMMainEnginePlantsService mainEnginePlantsService;


    @GetMapping("/list")
    public Result<IPage<MMotorPart>> list(MMotorPart motorPart,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<MMotorPart>> result = Result.ok();
        Page<MMotorPart> page = new Page<>(pageNo, pageSize);

        IPage<MMotorPart> pageList = motorPartService.selectPage(page, motorPart);

        result.setResult(pageList);
        return result;
    }

    @PutMapping("/update")
    public Result<MMotorPart> update(@RequestBody MMotorPart motorPart) {
        Result<MMotorPart> result = new Result<>();

        motorPartService.updateAndReBuildRelations(motorPart);

        return result;
    }

    @DeleteMapping("/delete")
    public Result<?> delete(@RequestParam("id") String id) {
        motorPartService.removeById(id);

        return Result.ok();
    }

    @PostMapping("/add")
    public Result<?> add(@RequestBody MMotorPart motorPart) {
        Result<MMotorPart> result = new Result<>();


        motorPart.setCreateBy(OauthUtils.getCurrentUser().getUserId());
        motorPart.setUpdateBy(OauthUtils.getCurrentUser().getUserId());

        motorPartService.saveAndBuildRelations(motorPart);

        return result;
    }

    @GetMapping("/getApplicationMotorModelDict")
    public Result<List<MApplicationMotorModel>> getApplicationMotorModelDict() {
        Result<List<MApplicationMotorModel>> result = new Result<>();
        List<MApplicationMotorModel> list = applicationMotorModelService.list(
                new LambdaQueryWrapper<MApplicationMotorModel>().select(MApplicationMotorModel::getName, MApplicationMotorModel::getMotorType)
        );
        result.setResult(list);
        return result;
    }

    @GetMapping("/getPartTypeDict")
    public Result<List<MPartType>> getPartTypeDict() {
        Result<List<MPartType>> result = new Result<>();
        List<MPartType> list = partTypeService.list(
                new LambdaQueryWrapper<MPartType>().select(MPartType::getName, MPartType::getPartType)
        );
        result.setResult(list);
        return result;
    }

    @GetMapping("/getMainEngineRelsDict")
    public Result<List<MMainEnginePlants>> getMainEngineRelsDict() {
        Result<List<MMainEnginePlants>> result = new Result<>();
        List<MMainEnginePlants> list = mainEnginePlantsService.list(
                new LambdaQueryWrapper<MMainEnginePlants>().select(MMainEnginePlants::getName, MMainEnginePlants::getMainEngineNo)
        );
        result.setResult(list);
        return result;
    }

    @GetMapping("/getRelsByPartId")
    public Result<Map<String, Object>> getRelsByPartId(String id) {
        Result<Map<String, Object>> result = new Result<>();

        Map<String, Object> map = motorPartService.getRelsByPartId(id);
        result.setResult(map);
        return result;
    }

    @PostMapping("/downloadPartTemplate")
    public void downloadPartTemplate(HttpServletResponse response) {
        String filePath = "templates/货品清单导入模板.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + FileUtil.getName(filePath));
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(classPathResource.getFile());
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载货品清单模板时发生异常", e);
        }
        try {
            if (!Objects.isNull(bis)) bis.close();
            if (!Objects.isNull(fis)) fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/importMotorPartExcel")
    public Result<Object> uploadMotorPartExcel(@Valid @NotNull MultipartFile file) {

        try {

            EasyExcel.read(file.getInputStream(), MotorPartExcelDto.class, new MotorPartExcelListener(motorPartService))
                    .sheet("货品清单").doRead();


        } catch (IOException e) {
            e.printStackTrace();
        }


        return Result.ok();
    }
}
